package com.qianjiangcloud.store.activity;

import java.util.ArrayList;
import java.util.Arrays;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;


import com.qianjiangcloud.store.libary.cache.MyImageLoader;

import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.SimpleTextWatcher;
import com.qianjiangcloud.store.http.JsonRequestBean;
import com.qianjiangcloud.store.http.JsonTask;
import com.qianjiangcloud.store.http.JsonTaskHandler;
import com.qianjiangcloud.store.ui.MyGroupContainer;
import com.qianjiangcloud.store.ui.RushBuyCountDownTimerView;
import com.qianjiangcloud.store.ui.pulltorefresh.lib.PullToRefreshBase;
import com.qianjiangcloud.store.ui.pulltorefresh.lib.PullToRefreshGridView;

import com.qianjiangcloud.store.R;

public class SearchFragment extends BaseDoFragment  {
    private final String KEY_GOODS_SERCH_HISTORY = "goods_serach_history";
    //关键字接口
    private final String KEYWORDS_SEPARATOR = ",";

    private EditText mKeywordsText;
    private MyGroupContainer mContentViews;
    private LinearLayout historyListView;
    private JsonTask mAssociateTask;
    private boolean isFromGoodsList;
    private SharedPreferences sp;
    private ListView hotListView;
    private GoodsListAdapter mGoodsListAdapter;
    private int index = 0;
    private ScrollView searchscroll;
    private String newTime;
    private int mPageNum;

    //历史收索
    private ArrayList<String> mGoodsKeywords = new ArrayList<String>();
    //热门收索
    private ArrayList<String> mHotKeywords = new ArrayList<String>();
    //联想收索
    private ArrayList<String> mAssociateKeywords = new ArrayList<String>();
    //结果
    private ArrayList<JSONObject> mGoodsArray = new ArrayList<JSONObject>();
    private ListView mAssociateListView;
    private Long textChangeTime = 0L;
    private PullToRefreshGridView goodListListView;
    private LayoutInflater mLayoutInflater;
    private JsonTask mTask;
    private String mKeywords;
    private boolean isAssociate = true;
    private RelativeLayout empty_rl;
    boolean isScrolling;
    private int i=1;
    //最后的列表的id
    String last_id="";
    //最大的历史记录
    private int maxHistoryRecord=6;

    public SearchFragment() {
        super();

    }

    @Override
    public void init(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
        mLayoutInflater = mActivity.getLayoutInflater();
        //热门收索加载数据
        Run.excuteJsonTask(new JsonTask(), new HotSearchTask());



        mActionBar.setShowTitleBar(false);

        rootView = inflater.inflate(R.layout.fragment_search, null);

        //联想收索初始化
        mAssociateListView = (ListView) findViewById(R.id.list_associate);
        //初始化ListView，历史
        historyListView = (LinearLayout) findViewById(R.id.container_ll);
        //当收索不到数据布局初始化
        empty_rl = (RelativeLayout) findViewById(R.id.empty_ui_rl);
        //收索结果初始化
        goodListListView = (PullToRefreshGridView) findViewById(R.id.search_goods_list_listview);
        goodListListView.setPullToRefreshEnabled(true);
//        goodListListView.set

        mGoodsListAdapter = new GoodsListAdapter();
        goodListListView.getRefreshableView().setAdapter(mGoodsListAdapter);
        goodListListView.getRefreshableView().setOnItemClickListener(
                new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        JSONObject json = (JSONObject) view
                                .getTag(R.id.tag_object);
                        String goodsIID = json.optString("goods_id");
                        Intent intent = AgentActivity.intentForFragment(
                                mActivity, AgentActivity.FRAGMENT_GOODS_DETAIL)
                                .putExtra(Run.EXTRA_CLASS_ID, goodsIID);
                        startActivity(intent);

                    }

                });
        hotListView = (ListView) findViewById(R.id.list1);
        //历史收索加载数据，
        loadKeywordsHistory();
         //控制历史记录是否显示
        controlHistoryShow();

        searchscroll = (ScrollView) findViewById(R.id.search_scroll);
        mAssociateListView.setAdapter(new AssKeywordsAdapter());

        hotListView.setAdapter(new HotAdapter());

//        //处理ScrollView嵌套ListViewbug问题
//        setListViewHeightBasedOnChildren(historyListView);


        //mContentViews = (MyGroupContainer) findViewById(android.R.id.content);
        mKeywordsText = (EditText) findViewById(android.R.id.edit);
        Bundle b = getArguments();
        if (b != null) {
            String keyword = b.getString(Run.EXTRA_KEYWORDS);
            isFromGoodsList = b.getBoolean("com.shopex.westore.EXTRA_METHOD");
            if (!TextUtils.isEmpty(keyword)) {
                mKeywordsText.setText(keyword);
                mKeywordsText.setSelection(keyword.length());
            }
        }
        //findViewById(R.id.search_history_clear).setOnClickListener(this);
        //清除历史，设置点击事件
        findViewById(R.id.search_history_clear_new).setOnClickListener(this);
        //findViewById(R.id.search_hot_goods_refresh).setOnClickListener(this);

//        ((RadioButton) findViewById(R.id.search_history))
//                .setOnCheckedChangeListener(this);
//        ((RadioButton) findViewById(R.id.search_hot_goods))
//                .setOnCheckedChangeListener(this);
//        ((RadioButton) findViewById(R.id.search_history)).setChecked(true);

        mKeywordsText.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    isAssociate = false;
                    empty_rl.setVisibility(View.GONE);
                    mAssociateListView.setVisibility(View.GONE);
                    //搜索输入为空就不请求
                    if (!"".equals(mKeywordsText.getText().toString().trim()))
                    {
                        startSearchAction(mKeywordsText.getText().toString());
                    }

                    return true;
                }
                return false;
            }
        });
        mAssociateListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                isAssociate = false;
                startSearchAction(mAssociateKeywords.get(position));
            }
        });

        hotListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //startSearchAction(mAssociateKeywords.get(position));
                isAssociate = false;
                startSearchAction(mHotKeywords.get(position));
            }
        });

        mKeywordsText.addTextChangedListener(new SimpleTextWatcher() {


            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //获取文本改变时间
//                textChangeTime = System.currentTimeMillis();

            }


            @Override
            public void afterTextChanged(Editable s) {
                mGoodsArray.clear();
                if (TextUtils.isEmpty(s.toString())) {
                    mAssociateListView.setVisibility(View.GONE);
                    searchscroll.setVisibility(View.VISIBLE);
                    goodListListView.setVisibility(View.GONE);
                    empty_rl.setVisibility(View.GONE);
                    return;
                }
                //获取改变后的时间
                Long currentTime = System.currentTimeMillis();

               // Log.e("rRaymond Debug", "" + currentTime + textChangeTime);

                if (currentTime - textChangeTime >=300L) {
                    //getSuggestionFromService()
                    // 取消前一个任务

                    if (mAssociateTask != null && mAssociateTask.isExcuting)
                        mAssociateTask.cancel(true);
                    mAssociateKeywords.clear();
                    if (isAssociate) {
                        mAssociateTask = new JsonTask();
                        //Toast.makeText(mActivity, "fdsfa", Toast.LENGTH_LONG).show();
                        //用户输入字符为空，就不去请求
                        if (!"".equals(s.toString().trim()))
                        {
                            Run.excuteJsonTask(mAssociateTask,
                                    new SearchAssociateTask(s.toString().trim()));
                            goodListListView.setVisibility(View.GONE);
                        }
                    }
                    // Log.e("rRaymond Debug", "after text changed if");
                    textChangeTime = currentTime;
                }


                searchscroll.setVisibility(View.GONE);
                mAssociateListView.setVisibility(View.VISIBLE);

            }
        });


        mKeywordsText.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ((EditText)v).setCursorVisible(true);
                last_id="";
                i=2;
                mGoodsArray.clear();
                empty_rl.setVisibility(View.GONE);
                if (((EditText)v).hasFocus()&&((EditText) v).getText().length()>0)
                {
                    if (mGoodsArray.size()==0) {
                        if (mTask != null && mTask.isExcuting) {
                            mTask.cancel(true);
                        }
                    }else {
                        mGoodsArray.clear();
                        if (mAssociateTask != null && mAssociateTask.isExcuting)
                            mAssociateTask.cancel(true);
                          mAssociateKeywords.clear();
                        //当请求商品结果，完毕后，再次点击editText，为空时就不请求
                        if ("".equals(((EditText) v).getText().toString().trim()))
                        {
                            mAssociateTask = new JsonTask();
                            Run.excuteJsonTask(mAssociateTask,
                                    new SearchAssociateTask(((EditText) v).getText().toString().trim()));
                            mAssociateListView.setVisibility(View.VISIBLE);
                        }
                    }
                    mGoodsListAdapter.notifyDataSetChanged();
                    goodListListView.setVisibility(View.GONE);
                    mAssociateListView.setVisibility(View.VISIBLE);
                }
            }
        });


        goodListListView.setOnScrollListener(new AbsListView.OnScrollListener() {



            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                isScrolling = false;
					//mGoodsListAdapter.notifyDataSetChanged();
				} else {
					isScrolling = true;
				}
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                if (totalItemCount < 3)
                    return;

                // 滚动到倒数第五个时，自动加载下一页
                if (totalItemCount - (firstVisibleItem + visibleItemCount) <= 3&&isScrolling) {
                      if(!TextUtils.equals("null",last_id)){
                          loadNextPage(last_id);

                      }else {
                          if (i==1)
                          {
                              Toast.makeText(mActivity, "没有更多数据了哦", Toast.LENGTH_SHORT).show();
                          }
                            i=2;
                      }
                }
            }
        });
        goodListListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadNextPage("");
            }

            @Override
            public void onRefreshMore() {
//                loadNextPage(last_id);
            }
        });
        findViewById(R.id.fragment_search_cancel).setOnClickListener(this);
        findViewById(R.id.fragment_search_search).setOnClickListener(this);

    }
    //控制历史记录是否显示
    private void controlHistoryShow()
    {
    //作判断当历史记录的集合长度为0的时候不显示
        if (mGoodsKeywords.size() <= 0) {
            historyListView.setVisibility(View.GONE);
            findViewById(R.id.tv_search_history).setVisibility(View.GONE);
            findViewById(R.id.ll_history).setVisibility(View.GONE);
            return;
        }
        historyListView.setVisibility(View.VISIBLE);
        findViewById(R.id.tv_search_history).setVisibility(View.VISIBLE);
        findViewById(R.id.ll_history).setVisibility(View.VISIBLE);
    }
//    @Override
//    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//        if (isChecked) {
//            findViewById(R.id.search_history_clear).setVisibility(View.GONE);
//            findViewById(R.id.search_history_closely_label).setVisibility(
//                    View.GONE);
//            findViewById(R.id.search_hot_goods_refresh)
//                    .setVisibility(View.GONE);
//            if (buttonView.getId() == R.id.search_history) {
//                findViewById(R.id.search_history_clear).setVisibility(
//                        View.VISIBLE);
//                findViewById(R.id.search_history_closely_label).setVisibility(
//                        View.VISIBLE);
//                loadKeywordsHistory();
//            } else if (buttonView.getId() == R.id.search_hot_goods) {
//                findViewById(R.id.search_hot_goods_refresh).setVisibility(
//                        View.VISIBLE);
//                // 加载热门关键词       一次访问取回所有的热门关键字
//                mContentViews.removeAllViews();
//                if (mHotKeywords.size() > 0) {
//                    addKeywordView(mHotKeywords, 0);
//                } else {
//                    Run.excuteJsonTask(new JsonTask(), new HotSearchTask());
//                }
//            }
//        }
//    }

    // 开始搜索
    private void startSearchAction(String keywords) {
        //开始检索商品结果列表时，来隐藏存在的空界面
        empty_rl.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(keywords)) {
            if (mGoodsKeywords.contains(keywords)) {
                mGoodsKeywords.remove(keywords);
            }

            if (mGoodsKeywords.size()>=maxHistoryRecord)
            {
                mGoodsKeywords.remove(maxHistoryRecord-1);
            }
            mGoodsKeywords.add(0, keywords);
//            setListViewHeightBasedOnChildren(historyListView);
            saveSearchHistory(KEY_GOODS_SERCH_HISTORY, mGoodsKeywords);

            mGoodsKeywords.clear();
            historyListView.removeAllViews();
            loadKeywordsHistory();
            controlHistoryShow();

            if (isFromGoodsList) {
                Intent data = new Intent();
                data.putExtra(Run.EXTRA_KEYWORDS, keywords);
                mActivity.setResult(Activity.RESULT_OK, data);
            } else {
//               mActivity.startActivity(AgentActivity
//                        .intentForFragment(mActivity,
//                                AgentActivity.FRAGMENT_GOODS_LIST)
//                        .putExtra(Run.EXTRA_KEYWORDS, keywords)
//                        .putExtra(Run.EXTRA_TITLE, keywords));
                mAssociateListView.setVisibility(View.GONE);
                //在请求结果列表的时候将原来联想结果请求移除
                if (mAssociateTask != null && mAssociateTask.isExcuting)
                    mAssociateTask.cancel(true);

                mAssociateKeywords.clear();
                mKeywords = keywords.trim();
                InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

                mKeywordsText.setText(keywords);
               // mKeywordsText.setSelection(keywords.length());
                mKeywordsText. setCursorVisible(false);
                isAssociate = true;
                loadNextPage(last_id);



            }
            //mActivity.finish();
        }
    }

    /* 加载搜索历史记录 */
    private void loadKeywordsHistory() {
        // 商品搜索历史
        mGoodsKeywords.clear();
        String keywords = Run.loadOptionString(mActivity,
                KEY_GOODS_SERCH_HISTORY, "");
        if (!TextUtils.isEmpty(keywords))
            mGoodsKeywords.addAll(Arrays.asList(keywords
                    .split(KEYWORDS_SEPARATOR)));
      for (int i=0;i<mGoodsKeywords.size();i++)
     {
         loadView(mGoodsKeywords.get(i).toString());
     }
        //addKeywordView(mGoodsKeywords, 1);
    }

    private void loadView(String str) {
        View view = mLayoutInflater.inflate(R.layout.item_help_centre, null);
        ((TextView) view.findViewById(R.id.item_help_centre_title)).setText(str);
        ( historyListView).addView(view);
        view.setOnClickListener(listener);
        view.setTag(str);
    }

    private OnClickListener listener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getTag() != null) {
                //JSONObject data = (JSONObject) v.getTag();
                isAssociate = false;
                startSearchAction(v.getTag().toString());
            }
        }
    };
    /**
     * @param keywords
     * @param type     0: 热门关键字每次只显示10    1:搜索历史全部显示
     */
    private void addKeywordView(ArrayList<String> keywords, int type) {
        index = 0;
        if (type == 1) {
            mContentViews.removeAllViews();
            LayoutInflater inf = mActivity.getLayoutInflater();
            for (String text : keywords) {
                View view = inf.inflate(R.layout.fragment_search_item, null);
                ((TextView) view.findViewById(android.R.id.text1)).setText(text);
                view.findViewById(android.R.id.text1).setOnClickListener(
                        mItemClickListener);
                mContentViews.addView(view);
            }
        } else {
            setShowTextList();
        }
    }

    /**
     * 获取接下来的要显示的热门关键字
     *
     * @author chesonqin
     * 2014-11-25
     */
    private void setShowTextList() {
        mContentViews.removeAllViews();
        int row = mHotKeywords.size() / 10 + (mHotKeywords.size() % 10 == 0 ? 0 : 1);
        if (row == 0) {
            return;
        }
        ArrayList<String> showList = new ArrayList<String>();
        index = index % row;
        if (index == row - 1) {
            if (mHotKeywords.size() >= 10) {
                for (int i = mHotKeywords.size() - 10; i < mHotKeywords.size(); i++) {
                    System.out.print(mHotKeywords.get(i) + "   ");
                    showList.add(mHotKeywords.get(i));
                }
            } else {
                for (int i = index * 10; i < mHotKeywords.size(); i++) {
                    showList.add(mHotKeywords.get(i));
                }
            }
        } else {
            for (int i = index * 10; i < (index + 1) * 10; i++) {
                showList.add(mHotKeywords.get(i));
            }
        }

        LayoutInflater inf = mActivity.getLayoutInflater();
        for (String text : showList) {
            View view = inf.inflate(R.layout.fragment_search_item, null);
            ((TextView) view.findViewById(android.R.id.text1)).setText(text);
            view.findViewById(android.R.id.text1).setOnClickListener(
                    mItemClickListener);
            mContentViews.addView(view);
        }
        index++;
    }

    private OnClickListener mItemClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            String keyword = ((TextView) v).getText().toString();
            if (mGoodsKeywords.contains(keyword)) {
                mGoodsKeywords.remove(keyword);
            }
            mGoodsKeywords.add(0, keyword);
            saveSearchHistory(KEY_GOODS_SERCH_HISTORY, mGoodsKeywords);
            if (isFromGoodsList) {
                Intent data = new Intent();
                data.putExtra(Run.EXTRA_KEYWORDS, keyword);
                mActivity.setResult(Activity.RESULT_OK, data);
            } else {
                mActivity.startActivity(AgentActivity
                        .intentForFragment(mActivity,
                                AgentActivity.FRAGMENT_GOODS_LIST)
                        .putExtra(Run.EXTRA_KEYWORDS, keyword)
                        .putExtra(Run.EXTRA_TITLE, keyword));
            }
            mActivity.finish();
        }
    };

    @Override
    public void onStop() {
        super.onStop();

//		saveSearchHistory(KEY_GOODS_SERCH_HISTORY, mGoodsKeywords);
    }

    @Override
    public void onDestroy() {

        //销毁把请求，取消请求
        super.onDestroy();
        if (mAssociateTask != null && mAssociateTask.isExcuting)
            mAssociateTask.cancel(true);
        if (mTask != null && mTask.isExcuting) {
            mTask.cancel(true);
        }
    }

    // 保存搜索历史
    private void saveSearchHistory(String key, ArrayList<String> keywords) {
        String savedKeywords = Run.EMPTY_STR;
//		for (int i = 0, c = keywords.size(); i < 10 && i < c; i++) {
//			savedKeywords = Run.buildString(savedKeywords,
//					(i == 0) ? Run.EMPTY_STR : KEYWORDS_SEPARATOR, keywords
//							.get(i).replaceAll(KEYWORDS_SEPARATOR, ""));
//		}
        for (int i = 0, c = keywords.size(); i < c; i++) {
            savedKeywords = Run.buildString(savedKeywords,
                    (i == 0) ? Run.EMPTY_STR : KEYWORDS_SEPARATOR, keywords
                            .get(i).replaceAll(KEYWORDS_SEPARATOR, ""));
        }
        Run.savePrefs(mActivity, key, savedKeywords);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.fragment_search_cancel) {
            mActivity.finish();
        } else if (v.getId() == R.id.fragment_search_search) {
            startSearchAction(mKeywordsText.getText().toString());
        } else if (v.getId() == R.id.search_history_clear_new) {
            mGoodsKeywords.clear();
            historyListView.removeAllViews();
            historyListView.setVisibility(View.GONE);
            findViewById(R.id.tv_search_history).setVisibility(View.GONE);
            findViewById(R.id.ll_history).setVisibility(View.GONE);
            //mContentViews.removeAllViews();
            saveSearchHistory(KEY_GOODS_SERCH_HISTORY, mGoodsKeywords);
        } else {
            super.onClick(v);
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Run.showSoftInputMethod(mActivity, mKeywordsText);
            }
        }, 500);
    }

    private class HotSearchTask implements JsonTaskHandler {
        @Override
        public JsonRequestBean task_request() {
            showCancelableLoadingDialog();
            return new JsonRequestBean(
                    "mobileapi.keywords.get_all_list");
        }

        @Override
        public void task_response(String json_str) {
            hideLoadingDialog_mt();
            try {
                JSONObject all = new JSONObject(json_str);
                JSONObject data = all.optJSONObject("data");
                JSONArray array = data.optJSONArray("items");
                // mHotKeywords.clear();
                for (int i = 0, len = array.length(); i < len; i++) {

                    mHotKeywords.add(array.getJSONObject(i)
                            .optString("kw_name"));
                    //addKeywordView(mHotKeywords, 0);
                }
                hotListView.setAdapter(new HotAdapter());
                setListViewHeightBasedOnChildren(hotListView);

            } catch (Exception e) {
            }
        }
    }

    private class SearchAssociateTask implements JsonTaskHandler {
        private String key = Run.EMPTY_STR;

        //key  联想的关键字
        public SearchAssociateTask(String key) {
            this.key = key;
        }

        @Override
        public JsonRequestBean task_request() {
            return new JsonRequestBean(
                    "mobileapi.keywords.get_guess_list").addParams("key",
                    this.key);
        }

        @Override
        public void task_response(String json_str) {
            try {
                JSONObject all = new JSONObject(json_str);
                JSONObject array = all.optJSONObject("data");
                JSONArray items = array.optJSONArray("items");
                mAssociateKeywords.clear();
                //联想搜索结果为空的时候，显示为空的界面
                if (items.length()==0)
                {
                    mAssociateListView.setVisibility(View.GONE);
                   //empty_rl.setVisibility(View.VISIBLE);
                }
                for (int i = 0, len = items.length(); i < len; i++)
                    mAssociateKeywords.add(items.getJSONObject(i).optString("kw_name"));
                ((BaseAdapter) mAssociateListView.getAdapter())
                        .notifyDataSetChanged();
                // mAssociateListView.setAdapter(new AssKeywordsAdapter());
            } catch (Exception e) {
            }
        }
    }

    public class HistoryAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mGoodsKeywords == null ? 0 : mGoodsKeywords.size();
        }

        @Override
        public Object getItem(int arg0) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(
                        R.layout.item_help_centre, null);
                convertView.findViewById(R.id.item_help_centre_arrow)
                        .setVisibility(View.VISIBLE);
            }

            TextView tv = (TextView) convertView
                    .findViewById(R.id.item_help_centre_title);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            tv.setText(mGoodsKeywords.get(position));
            convertView.findViewById(R.id.account_home_item_divider_martop)
                    .setVisibility(View.GONE);
            convertView.findViewById(R.id.account_home_item_divider_b2)
                    .setVisibility(View.GONE);
            convertView.findViewById(R.id.account_home_item_divider_t)
                    .setVisibility(View.GONE);

            if (position == 0) {
                convertView.findViewById(R.id.account_home_item_divider_t)
                        .setVisibility(View.VISIBLE);
                convertView.findViewById(R.id.account_home_item_divider_b1)
                        .setVisibility(View.VISIBLE);
                if (getCount() == 1) {
                    convertView.findViewById(R.id.account_home_item_divider_b1)
                            .setVisibility(View.GONE);
                    convertView.findViewById(R.id.account_home_item_divider_b2)
                            .setVisibility(View.VISIBLE);
                }
            } else if (position == getCount() - 1) {
                convertView.findViewById(R.id.account_home_item_divider_b1)
                        .setVisibility(View.GONE);
                convertView.findViewById(R.id.account_home_item_divider_b2)
                        .setVisibility(View.VISIBLE);
            }

            return convertView;
        }

    }

    public class AssKeywordsAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mAssociateKeywords == null ? 0 : mAssociateKeywords.size();
        }

        @Override
        public Object getItem(int arg0) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(
                        R.layout.item_help_centre, null);
                convertView.findViewById(R.id.item_help_centre_arrow)
                        .setVisibility(View.VISIBLE);
                convertView.findViewById(R.id.search_item_iv).setVisibility(View.VISIBLE);
            }

            TextView tv = (TextView) convertView
                    .findViewById(R.id.item_help_centre_title);
            tv.setText(mAssociateKeywords.get(position));
            convertView.findViewById(R.id.account_home_item_divider_martop)
                    .setVisibility(View.GONE);
            convertView.findViewById(R.id.account_home_item_divider_b2)
                    .setVisibility(View.GONE);
            convertView.findViewById(R.id.account_home_item_divider_t)
                    .setVisibility(View.GONE);

            if (position == 0) {
                convertView.findViewById(R.id.account_home_item_divider_t)
                        .setVisibility(View.VISIBLE);
                convertView.findViewById(R.id.account_home_item_divider_b1)
                        .setVisibility(View.VISIBLE);
                if (getCount() == 1) {
                    convertView.findViewById(R.id.account_home_item_divider_b1)
                            .setVisibility(View.GONE);
                    convertView.findViewById(R.id.account_home_item_divider_b2)
                            .setVisibility(View.VISIBLE);
                }
            } else if (position == getCount() - 1) {
                convertView.findViewById(R.id.account_home_item_divider_b1)
                        .setVisibility(View.GONE);
                convertView.findViewById(R.id.account_home_item_divider_b2)
                        .setVisibility(View.VISIBLE);
            }

            return convertView;
        }

    }

    public class HotAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mHotKeywords == null ? 0 : mHotKeywords.size();
        }

        @Override
        public Object getItem(int arg0) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(
                        R.layout.item_help_centre, null);
                convertView.findViewById(R.id.item_help_centre_arrow)
                        .setVisibility(View.VISIBLE);
            }

            TextView tv = (TextView) convertView
                    .findViewById(R.id.item_help_centre_title);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            tv.setText(mHotKeywords.get(position));
            convertView.findViewById(R.id.account_home_item_divider_martop)
                    .setVisibility(View.GONE);
            convertView.findViewById(R.id.account_home_item_divider_b2)
                    .setVisibility(View.GONE);
            convertView.findViewById(R.id.account_home_item_divider_t)
                    .setVisibility(View.GONE);

            if (position == 0) {
                convertView.findViewById(R.id.account_home_item_divider_t)
                        .setVisibility(View.VISIBLE);
                convertView.findViewById(R.id.account_home_item_divider_b1)
                        .setVisibility(View.VISIBLE);
                if (getCount() == 1) {
                    convertView.findViewById(R.id.account_home_item_divider_b1)
                            .setVisibility(View.GONE);
                    convertView.findViewById(R.id.account_home_item_divider_b2)
                            .setVisibility(View.VISIBLE);
                }
            } else if (position == getCount() - 1) {
                convertView.findViewById(R.id.account_home_item_divider_b1)
                        .setVisibility(View.GONE);
                convertView.findViewById(R.id.account_home_item_divider_b2)
                        .setVisibility(View.VISIBLE);
            }

            return convertView;
        }

    }

    /***
     * 动态设置listview的高度
     *
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    private void loadNextPage(String mLast_id) {
        if (mTask != null && mTask.isExcuting) {
            return;
        }
        //this.mPageNum = oldPageNum + 1;

//        if (this.mPageNum == 1) {
//            mGoodsListAdapter.notifyDataSetChanged();
//            goodListListView.setRefreshing();
//        }//            mGoodsArray.clear();

        if(!"null".equals(mLast_id)){
            if ("".equals(mLast_id))
            {
                mGoodsArray.clear();
                mGoodsListAdapter.notifyDataSetChanged();
                goodListListView.setRefreshing();
            }

            last_id=mLast_id;
            mTask = new JsonTask();
            Run.excuteJsonTask(mTask, new GetGoodsTask(mKeywords));
        }


    }

    private void loadLocalGoods(JSONObject json) {

        JSONArray item = json.optJSONArray("items");
        hideLoadingDialog();
        //收索结果为空的时候显示为空的界面
        if (item.length()==0)
        {
            goodListListView.setVisibility(View.GONE);
            empty_rl.setVisibility(View.VISIBLE);
        }
        if (item != null && item.length() > 0) {
//			mGoodsArray.clear();
            for (int i = 0; i < item.length(); i++) {
                mGoodsArray.add(item.optJSONObject(i));
            }
            mGoodsListAdapter.notifyDataSetChanged();
            //goodListListView.getRefreshableView().setAdapter(mGoodsListAdapter);
            goodListListView.setVisibility(View.VISIBLE);
            empty_rl.setVisibility(View.GONE);

        }

    }

    class GetGoodsTask implements JsonTaskHandler {
        private String mKeywords;

        GetGoodsTask(String mKeywords) {

            super();
            this.mKeywords = mKeywords;
        }

        @Override
        public void task_response(String json_str) {
            try {
//                hideLoadingDialog_mt();
                goodListListView.onRefreshComplete();
                JSONObject all = new JSONObject(json_str);
                if (Run.checkRequestJson(mActivity, all)) {
                    JSONObject childs = all.optJSONObject("data");
                   // Log.e("tag",childs.toString());
                    last_id =childs.optString("last_id");
                    //来判断这是一个滚动时候加载，还是直接去请求
                    if (TextUtils.equals("null",last_id)&&isScrolling)
                    {
                        //Toast.makeText(mActivity,"没有更多数据了哦",Toast.LENGTH_LONG).show();
                        return;
                    }
                    newTime = childs.optString("system_time");
                    if (childs != null) {
                        //JSONObject items = childs.optJSONObject("items");
                       // if (items != null) {
                            loadLocalGoods(childs);
                        //}
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public JsonRequestBean task_request() {
            JsonRequestBean req = new JsonRequestBean(
                    "mobileapi.goods.get_search_list");
            //由pageNum转换last_id
            req.addParams("last_id", String.valueOf(last_id));
           // req.addParams("limit","3");
            if (!TextUtils.isEmpty(mKeywords))
                req.addParams("key", mKeywords);

            //req.addParams("son_object", "json");

            return req;
        }

    }


    //结果列表的Adapter
    private class GoodsListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mGoodsArray.size();
        }

        @Override
        public JSONObject getItem(int position) {
            return mGoodsArray.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = mLayoutInflater
                        .inflate(R.layout.goods_item, null);
                viewHolder.iconImage = (ImageView) convertView
                        .findViewById(R.id.fragment_goods_item_icon);
                viewHolder.titleTextView = (TextView) convertView
                        .findViewById(R.id.fragment_goods_item_title);
                viewHolder.priceTextView = (TextView) convertView
                        .findViewById(R.id.fragment_goods_item_price);
                viewHolder.statusTextView = (TextView) convertView
                        .findViewById(R.id.fragment_goods_item_status);
                viewHolder.timeTextView = (RushBuyCountDownTimerView) convertView
                        .findViewById(R.id.fragment_goods_item_time_buy);
                viewHolder.timeView = convertView
                        .findViewById(R.id.fragment_goods_item_time);
                viewHolder.soldImage = (ImageView) convertView
                        .findViewById(R.id.fragment_goods_item_sold);
                viewHolder.markPriceTextView = (TextView) convertView
                        .findViewById(R.id.fragment_goods_item_mark_price);
                viewHolder.timeTitleTextView = (TextView) convertView
                        .findViewById(R.id.fragment_goods_item_time_title);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            JSONObject goodsObject = getItem(position);
            convertView.setTag(R.id.tag_object, goodsObject);
            viewHolder.titleTextView
                    .setText(goodsObject.optString("name") + "\n");
            viewHolder.priceTextView.setText("￥"
                    + goodsObject.optString("price"));
          /*  mVolleyImageLoader.showImage(viewHolder.iconImage,
                    goodsObject.optString("wx_image_id"));*/
            MyImageLoader.displayDefaultImage(goodsObject.optString("image_default_url"),viewHolder.iconImage);

            String strPmt = goodsObject.optString("pmt_text");
         /*   if (!TextUtils.isEmpty(strPmt) && !"null".equals(strPmt)) {
                viewHolder.statusTextView.setText(strPmt);
                viewHolder.statusTextView.setVisibility(View.VISIBLE);
            } else {
                viewHolder.statusTextView.setVisibility(View.GONE);
            }*/
            int store = goodsObject.optInt("store");
            if (store <= 0) {
                viewHolder.soldImage.setVisibility(View.VISIBLE);
            } else {
                viewHolder.soldImage.setVisibility(View.GONE);
            }
            JSONArray SkusStatue = goodsObject.optJSONArray("skus");
            if (SkusStatue != null && SkusStatue.length() > 0) {
                JSONObject statueJSON = SkusStatue.optJSONObject(0);
                if (statueJSON != null) {
                    JSONObject infoJSON = statueJSON
                            .optJSONObject("starbuy_info");
                    if (infoJSON != null) {
                        if (infoJSON.optInt("type_id") == 2
                                && statueJSON.optBoolean("is_starbuy")) {
                            String endTime = infoJSON
                                    .optString("end_time");
                            int min = 0;
                            int hour = 0;
                            int sec = 0;
                            int time = Integer.parseInt(endTime) - Integer.parseInt(newTime);
                            sec = time;
                            if (sec > 60) {
                                min = sec / 60;
                                sec = sec % 60;
                            }
                            if (time > 60) {
                                hour = min / 60;
                                min = min % 60;
                            }

                            if (viewHolder.timeTextView.setTime(hour, min, sec)) {
                                viewHolder.timeView.setVisibility(View.VISIBLE);
                                viewHolder.timeTitleTextView.setText(getResources().getString(R.string.goods_item_time_end));
                                viewHolder.timeTextView.start();
                                viewHolder.markPriceTextView.setVisibility(View.VISIBLE);
                                viewHolder.markPriceTextView.setText("￥"
                                        + goodsObject.optString("market_price"));
                                viewHolder.markPriceTextView.getPaint().setFlags(
                                        Paint.STRIKE_THRU_TEXT_FLAG);
                            } else {
                                viewHolder.timeView.setVisibility(View.GONE);
                                viewHolder.markPriceTextView.setVisibility(View.GONE);
                            }
                        } else {
                            viewHolder.timeView.setVisibility(View.GONE);
                            viewHolder.markPriceTextView.setVisibility(View.GONE);
                        }
                    } else {
                        viewHolder.timeView.setVisibility(View.GONE);
                        viewHolder.markPriceTextView.setVisibility(View.GONE);
                    }
                } else {
                    viewHolder.timeView.setVisibility(View.GONE);
                    viewHolder.markPriceTextView.setVisibility(View.GONE);
                }
            } else {
                viewHolder.timeView.setVisibility(View.GONE);
                viewHolder.markPriceTextView.setVisibility(View.GONE);
            }

            return convertView;
        }
    }

    private class ViewHolder {
        private ImageView iconImage;
        private ImageView soldImage;
        private RushBuyCountDownTimerView timeTextView;
        private TextView titleTextView;
        private TextView priceTextView;
        private TextView markPriceTextView;
        private TextView statusTextView;
        private View timeView;
        private TextView timeTitleTextView;

    }

}